import {get} from "@/util/axios.js";
import VueCookie from 'vue-cookie';
import {ref , watchEffect} from "vue";
import {imgPath} from "@/util/index.js";


const error = ref(null);

export async function fetchUser() {
    try {
        const token = VueCookie.get('sessionId');
        if (!token) return;
        console.log('更新用户数据中……');
        await new Promise(((resolve, reject) => {
            get('/user/getUserMessage', {}, (res) => {
                localStorage.setItem('userInfo', JSON.stringify(res));
                getUser.value = res;
                console.log('更新用户数据成功！');
                res ? resolve(res) : reject(new Error('加载失败'));
            });
        })) // 更新数据
    } catch (err) {
        error.value = err.message; // 存储错误
    }
}


export const getUser = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'));


export const userIcon = ref(getUser.value?.icon ? imgPath(getUser.value.icon) : '/icon/default.jpg')


watchEffect(() => {
    try {
        if (getUser.value) {
            console.log('正在实时获取数据……');
            localStorage.setItem('userInfo', JSON.stringify(getUser.value))
            userIcon.value = getUser.value?.icon ? imgPath(getUser.value.icon) : '/icon/default.jpg'
            console.log(userIcon.value)
            console.log('实时获取数据成功！');
        }
    } catch (e) {
        console.error('存储失败:', e)
    }
})



export function logout() {
    VueCookie.delete('sessionId')
    localStorage.removeItem('userInfo')
}
